<template>
  <div class="media-library">
    <div class="media-header">
      <h2>媒体库</h2>
      <div class="header-actions">
        <button class="btn btn-primary" @click="triggerUpload">
          <i class="icon-upload"></i> 上传文件
        </button>
        <input 
          ref="fileInput" 
          type="file" 
          multiple 
          @change="handleFileUpload" 
          style="display: none;"
        />
      </div>
    </div>
    
    <div class="media-filters">
      <div class="filter-group">
        <label>文件类型:</label>
        <select v-model="filter.type">
          <option value="">全部</option>
          <option value="image">图片</option>
          <option value="video">视频</option>
          <option value="document">文档</option>
        </select>
      </div>
      <div class="filter-group">
        <input 
          type="text" 
          v-model="filter.search" 
          placeholder="搜索文件名..." 
          @keyup.enter="fetchMedia"
        />
      </div>
    </div>
    
    <div class="media-grid">
      <div 
        v-for="media in mediaItems" 
        :key="media.id" 
        class="media-item"
        :class="{ selected: selectedItems.includes(media.id) }"
        @click="toggleSelect(media.id)"
      >
        <div class="media-thumbnail">
          <img 
            v-if="media.media_type === 'image'" 
            :src="media.url" 
            :alt="media.name"
          />
          <div v-else class="file-icon">
            <i class="icon-file"></i>
          </div>
        </div>
        <div class="media-info">
          <div class="media-name">{{ media.name }}</div>
          <div class="media-meta">
            <span>{{ formatFileSize(media.size) }}</span>
            <span>{{ formatDate(media.create_time) }}</span>
          </div>
        </div>
        <div class="media-actions">
          <button @click.stop="copyUrl(media.url)" class="btn-icon">
            <i class="icon-copy"></i>
          </button>
          <button @click.stop="deleteMedia(media.id)" class="btn-icon danger">
            <i class="icon-delete"></i>
          </button>
        </div>
      </div>
    </div>
    
    <div class="media-pagination">
      <div class="pagination-info">
        共 {{ pagination.total }} 项，第 {{ pagination.page }} 页
      </div>
      <div class="pagination-controls">
        <button 
          :disabled="pagination.page <= 1" 
          @click="changePage(pagination.page - 1)"
        >
          上一页
        </button>
        <button 
          :disabled="pagination.page >= pagination.totalPages" 
          @click="changePage(pagination.page + 1)"
        >
          下一页
        </button>
      </div>
    </div>
    
    <!-- 批量操作栏 -->
    <div v-if="selectedItems.length > 0" class="bulk-actions">
      <div class="bulk-info">
        已选择 {{ selectedItems.length }} 项
      </div>
      <div class="bulk-buttons">
        <button class="btn btn-secondary" @click="clearSelection">取消选择</button>
        <button class="btn btn-danger" @click="deleteSelected">删除选中</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { mediaAPI } from '../../../api/index.js'

export default {
  name: 'MediaLibrary',
  setup() {
    const mediaItems = ref([])
    const selectedItems = ref([])
    const fileInput = ref(null)
    
    const pagination = ref({
      page: 1,
      size: 20,
      total: 0,
      totalPages: 0
    })
    
    const filter = ref({
      type: '',
      search: ''
    })
    
    const fetchMedia = async () => {
      try {
        const response = await mediaAPI.getMedia({
          page: pagination.value.page,
          size: pagination.value.size,
          type: filter.value.type,
          search: filter.value.search
        })
        
        mediaItems.value = response.data.media
        pagination.value.total = response.data.total
        pagination.value.totalPages = Math.ceil(response.data.total / pagination.value.size)
      } catch (error) {
        console.error('Failed to fetch media:', error)
      }
    }
    
    const triggerUpload = () => {
      fileInput.value.click()
    }
    
    const handleFileUpload = async (event) => {
      const files = Array.from(event.target.files)
      if (files.length === 0) return
      
      try {
        // 逐个上传文件
        for (const file of files) {
          const formData = new FormData()
          formData.append('file', file)
          
          await mediaAPI.uploadMedia(formData)
        }
        
        // 上传完成后刷新列表
        fetchMedia()
        event.target.value = '' // 清空input
      } catch (error) {
        console.error('Failed to upload files:', error)
        alert('文件上传失败')
      }
    }
    
    const toggleSelect = (id) => {
      const index = selectedItems.value.indexOf(id)
      if (index > -1) {
        selectedItems.value.splice(index, 1)
      } else {
        selectedItems.value.push(id)
      }
    }
    
    const clearSelection = () => {
      selectedItems.value = []
    }
    
    const deleteMedia = async (id) => {
      if (!confirm('确定要删除这个文件吗？')) return
      
      try {
        await mediaAPI.deleteMedia(id)
        fetchMedia()
        // 如果删除的是选中的项目，从选中列表中移除
        const index = selectedItems.value.indexOf(id)
        if (index > -1) {
          selectedItems.value.splice(index, 1)
        }
      } catch (error) {
        console.error('Failed to delete media:', error)
        alert('删除文件失败')
      }
    }
    
    const deleteSelected = async () => {
      if (selectedItems.value.length === 0) return
      if (!confirm(`确定要删除选中的 ${selectedItems.value.length} 个文件吗？`)) return
      
      try {
        await mediaAPI.deleteMultipleMedia(selectedItems.value)
        fetchMedia()
        selectedItems.value = []
      } catch (error) {
        console.error('Failed to delete selected media:', error)
        alert('批量删除文件失败')
      }
    }
    
    const copyUrl = (url) => {
      navigator.clipboard.writeText(url).then(() => {
        alert('URL已复制到剪贴板')
      }).catch(err => {
        console.error('Failed to copy URL:', err)
        alert('复制URL失败')
      })
    }
    
    const changePage = (page) => {
      pagination.value.page = page
      fetchMedia()
    }
    
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleDateString()
    }
    
    onMounted(() => {
      fetchMedia()
    })
    
    return {
      mediaItems,
      selectedItems,
      fileInput,
      pagination,
      filter,
      fetchMedia,
      triggerUpload,
      handleFileUpload,
      toggleSelect,
      clearSelection,
      deleteMedia,
      deleteSelected,
      copyUrl,
      changePage,
      formatFileSize,
      formatDate
    }
  }
}
</script>

<style scoped>
.media-library {
  padding: 20px;
}

.media-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.media-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions .btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.media-filters {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-group label {
  font-weight: 500;
  color: #2c3e50;
}

.filter-group input,
.filter-group select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.media-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.media-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.2s ease;
  position: relative;
  cursor: pointer;
}

.media-item:hover {
  border-color: #3498db;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.media-item.selected {
  border-color: #3498db;
  box-shadow: 0 0 0 2px #3498db;
}

.media-thumbnail {
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
}

.media-thumbnail img {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

.file-icon {
  font-size: 48px;
  color: #7f8c8d;
}

.media-info {
  padding: 10px;
}

.media-name {
  font-weight: 500;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.media-meta {
  font-size: 12px;
  color: #7f8c8d;
  display: flex;
  justify-content: space-between;
}

.media-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 5px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.media-item:hover .media-actions {
  opacity: 1;
}

.btn-icon {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  border: none;
  background: rgba(255, 255, 255, 0.9);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.btn-icon.danger {
  color: #e74c3c;
}

.media-pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.pagination-info {
  color: #2c3e50;
  font-weight: 500;
}

.pagination-controls button {
  padding: 8px 16px;
  margin: 0 5px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.bulk-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #3498db;
  color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

.bulk-info {
  font-weight: 500;
}

.bulk-buttons {
  display: flex;
  gap: 10px;
}

/* 图标样式 */
.icon-upload::before,
.icon-file::before,
.icon-copy::before,
.icon-delete::before {
  content: "📁"; /* 简化的图标表示 */
  font-style: normal;
}

.icon-upload::before { content: "⬆️"; }
.icon-file::before { content: "📄"; }
.icon-copy::before { content: "📋"; }
.icon-delete::before { content: "🗑️"; }
</style>